package com.i8office.android.zhihuixinwu.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.cyan.tools.annotation.ActivityFragmentInject;
import com.i8office.android.zhihuixinwu.R;
import com.i8office.android.zhihuixinwu.adapter.ScheduleByNameAdapter;
import com.i8office.android.zhihuixinwu.event.RefreshCalendarEvent;
import com.i8office.android.zhihuixinwu.module.contract.CalendarContract;
import com.i8office.android.zhihuixinwu.module.presenter.LeaderScheduleByNamePresenter;
import com.i8office.android.zhihuixinwu.ui.schedule.LeaderData;
import com.i8office.android.zhihuixinwu.ui.schedule.ScheduleData;
import com.i8office.android.zhihuixinwu.ui.schedule.ScheduleTask;
import com.i8office.android.zhihuixinwu.ui.schedule.ScheduleTaskContent;
import com.i8office.android.zhihuixinwu.widget.ItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import qdx.stickyheaderdecoration.NormalDecoration;
import view.recyclerview.CommonAdapter;
import view.recyclerview.ViewHolder;

@ActivityFragmentInject(
        contentViewId = R.layout.fragment_leader_schedule_by_name
)
public class LeaderScheduleByNameFragment extends BaseRefreshFragment<CalendarContract.LeaderScheduleByNamePresenter> implements CalendarContract.LeaderScheduleByNameView {
    @BindView(R.id.recyclerview1)
    RecyclerView recyclerView1;
    @BindView(R.id.recyclerview2)
    RecyclerView recyclerView2;
    @BindView(R.id.last_week_date)
    TextView mLastWeekDate;
    @BindView(R.id.next_week_date)
    TextView mNextWeekDate;
    private ScheduleData mScheduleData;
    private LeaderData.LeaderBean mCurrentLeader;
    private CommonAdapter<LeaderData.LeaderBean> mLeaderAdapter;
    private ScheduleByNameAdapter mScheduleAdapter;
    private Calendar mCalendar;
    private String mDate;
    private String mDateOfCurrentMonday;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    private RecyclerView.ItemDecoration decoration;

    public static LeaderScheduleByNameFragment newInstance() {

        Bundle args = new Bundle();

        LeaderScheduleByNameFragment fragment = new LeaderScheduleByNameFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView(View rootView) {
        ButterKnife.bind(this, rootView);
        mCalendar = Calendar.getInstance();
        mDate = format.format(mCalendar.getTimeInMillis());
        recyclerView1.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView1.setAdapter(mLeaderAdapter = new CommonAdapter<LeaderData.LeaderBean>(getActivity(), R.layout.item_leader_name) {
            @Override
            protected void convert(ViewHolder holder, final LeaderData.LeaderBean leaderBean, int position) {
                holder.getConvertView().setBackgroundColor(mCurrentLeader == leaderBean ? Color.WHITE : Color.TRANSPARENT);
                holder.setText(R.id.name, leaderBean.name);
                holder.getView(R.id.name).setSelected(mCurrentLeader == leaderBean);
                holder.setVisible(R.id.mark, mCurrentLeader == leaderBean);
                holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mCurrentLeader = leaderBean;
                        mDateOfCurrentMonday = "";
                        getSchedule();
                        notifyDataSetChanged();
                    }
                });
            }
        });

        recyclerView2.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView2.addItemDecoration(decoration = getDecoration());
        recyclerView2.addItemDecoration(new ItemDecoration(getActivity(), 1));
        recyclerView2.setAdapter(mScheduleAdapter = new ScheduleByNameAdapter(getActivity()));
        mPresenter = new LeaderScheduleByNamePresenter(this);
        mPresenter.getGroupLeaderData();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshEvent(RefreshCalendarEvent event) {
        if (mCurrentLeader != null) {
            getSchedule();
        }
    }

    private RecyclerView.ItemDecoration getDecoration() {
        NormalDecoration decoration = new NormalDecoration() {
            @Override
            public String getHeaderName(int pos) {
                try {
                    return mScheduleAdapter.getData().get(pos).getGroupTitle();
                } catch (Exception e) {
                    return null;
                }
            }
        };
        decoration.setOnDecorationHeadDraw(new NormalDecoration.OnDecorationHeadDraw() {
            @Override
            public View getHeaderView(int pos) {
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_schedule_title, null);
                ((TextView) view.findViewById(R.id.text)).setText(mScheduleAdapter.getData().get(pos).getGroupTitle());
                return view;
            }
        });
        return decoration;
    }


    @Override
    public void refresh() {

    }

    @Override
    public void showGroupLeaderData(List<LeaderData.LeaderBean> leaderData) {
        if (leaderData != null && leaderData.size() > 0) {
            mCurrentLeader = leaderData.get(0);
            getSchedule();
        }
        mLeaderAdapter.setList(leaderData);
    }

    private void getSchedule() {
        mPresenter.getLeaderScheduleByName(mCurrentLeader.id, mDate, mDateOfCurrentMonday);
    }

    @Override
    public void showLeaderScheduleByName(ScheduleData scheduleData) {
        if (scheduleData == null) {
            toast("服务器异常");
            return;
        }
        if (!scheduleData.Succeed) {
            if (TextUtils.isEmpty(scheduleData.Message)) {
                toast("服务器异常");
            } else {
                toast(scheduleData.Message);
            }
            return;
        }
        this.mScheduleData = scheduleData;
        List<ScheduleTask> scheduleTasks = new ArrayList<>();
        if (scheduleData != null) {
            for (ScheduleTaskContent content : scheduleData.Content) {
                if (content.Tasks != null && content.Tasks.size() > 0) {
                    for (ScheduleTask task : content.Tasks) {
                        task.setGroupTitle(content.Day + " " + content.Date);
                        scheduleTasks.add(task);
                    }
                } else {
                    ScheduleTask task = new ScheduleTask();
                    task.setGroupTitle(content.Day + content.Date);
                    scheduleTasks.add(task);
                }
            }
        }
        mScheduleAdapter.clear();
        mScheduleAdapter.addAll(scheduleTasks);
        recyclerView2.removeItemDecoration(decoration);
        recyclerView2.addItemDecoration(decoration = getDecoration());
        mLastWeekDate.setText(getWeekDate(scheduleData.DateTimeOfPrevMonday));
        mNextWeekDate.setText(getWeekDate(scheduleData.DateTimeOfNextMonday));
    }

    @OnClick(R.id.next)
    void nextWeek() {
        if (mCurrentLeader == null || mScheduleData == null) {
            return;
        }
        mDateOfCurrentMonday = mScheduleData.DateTimeOfNextMonday;
        getSchedule();
    }

    @OnClick(R.id.last)
    void lastWeek() {
        if (mCurrentLeader == null || mScheduleData == null) {
            return;
        }
        mDateOfCurrentMonday = mScheduleData.DateTimeOfPrevMonday;
        getSchedule();
    }

    private String getWeekDate(String dateStr) {
        StringBuffer sb = new StringBuffer();
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat format1 = new SimpleDateFormat("MM-dd");
            Date date = format.parse(dateStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(date.getTime());
            sb.append(format1.format(calendar.getTimeInMillis()));
            sb.append("~");
            calendar.add(Calendar.DAY_OF_MONTH, 6);
            sb.append(format1.format(calendar.getTimeInMillis()));
            return sb.toString();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }
}
